//
//  CZDetailViewController.swift
//  GZWeibo007
//
//  Created by danli on 15/12/24.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit
import SVProgressHUD
import SVPullToRefresh

///详情控制器
class CZDetailViewController: UIViewController,CZStatusCellDelegate ,UITableViewDataSource,UITableViewDelegate, CZCommentViewDelegate, CZStatusBottomViewDelegate{
    
    // MARK: - 属性
    /// 微博模
    private var status: CZStatus?
    
    /// 评论模型
    var comments : [CZComment]?{
        didSet
        {
            tableView.reloadData()
        }
    }
      // MARK: - 构造函数
    init(status: CZStatus) {
        self.status = status
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        title = "微博详情"
        prepareTableView()
        
        //添加底部View
        view.addSubview(bottomView)
        
        //约束不起作用
//        view.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSizeMake(UIScreen.mainScreen().bounds.width, 44))
        
        bottomView.translatesAutoresizingMaskIntoConstraints = false
        view.addConstraint(NSLayoutConstraint(item: bottomView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: bottomView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: bottomView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: UIScreen.mainScreen().bounds.width))
        view.addConstraint(NSLayoutConstraint(item: bottomView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 44))
     
    }
    
    // MARK: 实现tableView的代理方法
    /// tableView显示多少组
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        /// 显示2组, 第一组显示微博内容,第二组显示转发或评论
        return 2
    }
    
    /// 确定每组的行数
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            // 第0组显示微博内容.只有一个cell
            return 1
        } else
        {
            guard let length = comments?.count else
            {
                return 1
            }
            return length == 0 ? 1 : length
        }
    }
    
    // 确定每个cell的内容
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        // 第0组显示微博内容
        if indexPath.section == 0
        {
            let cellID = status!.cellID()
            let cell = tableView.dequeueReusableCellWithIdentifier(cellID) as! CZStatusCell
            
            // 设置cell的微博模型
            cell.status = status
            //设置代理
            if cell.self.isKindOfClass(CZStatusForwardCell)
            {
                let forwardcell = cell as! CZStatusForwardCell
                forwardcell.cellDelegate = self
            }
            cell.status = status
            
            return cell
        }
        else {
        
            if isloading == true && indexPath.row == 0
            {
                // 正在加载最新评论， 显示加载视图
                let cell = tableView.dequeueReusableCellWithIdentifier("loadingCell")!
                return cell
            }
            
            /// 当没有加载到评论内容前，显示“还没有人评论”
            let commentLength = comments?.count ?? 0 
            if commentLength == 0
            {
                let cell = tableView.dequeueReusableCellWithIdentifier("unCommitCell")!
                cell.textLabel?.text = "还没有人评论"
                cell.textLabel?.textAlignment = NSTextAlignment.Center
                return cell
            }

            // 显示评论 cell
            let cell = tableView.dequeueReusableCellWithIdentifier("CZCommentViewCell")! as! CZCommentViewCell
            cell.comment = self.comments![indexPath.row]
            return cell
        }
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        if indexPath.section == 0
        {
            // 模型中还未计算cell高度时计算
            if status?.rowHeight == nil
            {
                let cell = tableView.dequeueReusableCellWithIdentifier(status!.cellID()) as! CZStatusCell
                return cell.rowHeight(status!)
            }
            return status!.rowHeight!
        }
        return UITableViewAutomaticDimension
    }
    
    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 0
        {
            // 设置第0组和第1组的间隔
            return 10
        }
        return 0
    }
    
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
 
        // 为第一组设置-评论视图
        if section == 1
        {
           commentView.status = status
            return commentView
        }
        return nil
    }
    
    // 设置组头高度
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1
        {
            return 44
        }
        return 0
    }
    
    // MARK: - 实现底部view的代理方法
    func clickCommentButton() {
        // 创建跳转控制器，并且注册监听器
        let vc = CZComposeController(status: status!, vcType: CZComposeControllerType.composeControllerTypeComment)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "loadingNewComment", name: CZComposeNotification.commentNotification.rawValue, object: vc)
        
        
        presentViewController(UINavigationController(rootViewController: vc), animated: true, completion: nil)
    }
    
    func clickForwardButton() {
        
        // 当用户成功转发微博的时候，需要刷新一下主页的微博，在这里添加通知
        let vc = CZComposeController(status: status!, vcType: CZComposeControllerType.composeControllerTypeReport)
        
        //获取主页控制器
        let homeVC = self.navigationController?.childViewControllers[0]

        //注册监听器
        NSNotificationCenter.defaultCenter().addObserver(homeVC!, selector: "loadNewStatus", name: CZComposeNotification.reportNotification.rawValue, object: vc)
        presentViewController(UINavigationController(rootViewController: vc), animated: true, completion: nil)
    }
    
    func clickLickButton() {
        SVProgressHUD.showInfoWithStatus("还未实现点赞功能")
    }
    
    //MARK: 实现转发微博-CZStatusCellDelegate代理方法
    func retweetStatusClick(status: CZStatus){
        if let statu = status.retweeted_status
        {
            showDetailStatusViewController(statu)
        }
    }
    
    ///显示详情控制器
    private func showDetailStatusViewController(status: CZStatus) {
        let detailVC = CZDetailViewController(status: status)
        detailVC.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(detailVC, animated: true)
    }
    
    // MARK:实现评论视图-CZCommentViewDelegate的代理方法
    //点击评论按钮
    var isloading = false
    func commentViewBtnDidClick() {
        //加载评论
        isloading = true
        loadingNewComment()
    }
    
    // MARK: - 加载最新评论
    func loadingNewComment()
    {
        let since_id = self.comments == nil || self.comments!.count == 0 ? 0 : self.comments!.first!.id
        self.comments = self.comments == nil ? [CZComment()] :
        [CZComment()] + self.comments!
        
        self.status!.loadCommontInfo(0, since_id: since_id) { (comments, error) -> () in
             self.isloading = false
            self.comments?.removeFirst()
            if error != nil
            {
                print("加载评论数据出错, \(error)")
                return
            }
            
            guard let _ = self.comments else
            {
                self.comments = comments
                return
            }
            self.comments = comments! + self.comments!
        }
    }
    
    // MARK: - 加载更多评论
    func loadingMoreComment()
    {
        let max_id = self.comments == nil || self.comments?.count == 0 ? 0 : self.comments!.last!.id
        
        self.status!.loadCommontInfo(max_id, since_id: 0) { (comments, error) -> () in
            // 网络请求完成，移除底部的加载视图
            self.tableView.infiniteScrollingView.stopAnimating()
        
            if error != nil
            {
                print("加载评论数据出错, \(error)")
                return
            }
            
            guard let _ = self.comments else
            {
                self.comments = comments
                return
            }
            
            self.comments = self.comments! + comments!
        }
    }
    
    //MARK: 设置tableView
    private func prepareTableView(){
        // 添加子控件
        view.addSubview(tableView)
        tableView.estimatedRowHeight = 200
        tableView.delegate = self
        tableView.dataSource = self
        let size = UIScreen.mainScreen().bounds.size
        
        // 去除分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        tableView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: CGSizeMake(size.width, size.height - 44))
       
        // 注册cell
        tableView.registerClass(CZStatusNormalCell.self, forCellReuseIdentifier: CZStatusCellReuseIdentifier.StatusNormalCell.rawValue)
        tableView.registerClass(CZStatusForwardCell.self, forCellReuseIdentifier: CZStatusCellReuseIdentifier.StatusForwardCell.rawValue)
        tableView.registerClass(CZCommentViewCell.self, forCellReuseIdentifier: "CZCommentViewCell")
        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "unCommitCell")
        tableView.registerClass(CZLoadingCell.self, forCellReuseIdentifier: "loadingCell")
        
        // 设置上拉加载闭包
        tableView.addInfiniteScrollingWithActionHandler { () -> Void in
            self.loadingMoreComment()
        }
        
    }
    
    deinit
    {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // MARK: - 懒加载
    // tableView
    private lazy var tableView:UITableView = {
       let tabelView = UITableView()
        return tabelView
    }()
    
    private lazy var commentView:CZCommentView = {
       let view = CZCommentView()
        view.delegate = self
        
        return view
    }()
    
    private lazy var bottomView:CZStatusBottomView = {
        let bottomView = CZStatusBottomView()
        bottomView.delegate = self
        return bottomView
    }()
}
